import {getUserInfo,getLogin} from "@/api/login";
import {getToken, removeToken, setToken} from "@/utils/tokenUtils";
import qs from 'qs'

const user = {
    state: {//可共享的全局变量
        token: getToken(),
        userinfo:'',

    },
    mutations: {//定义修改变量的函数
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_LOGIN_STATUS: (state, status) => {
            state.loginStatus = status;
        },
        SET_USERINFO:(state, userinfo) => {
            state.userinfo = userinfo;
        },


    },
    actions: {
        Login({commit}, params) {
            return new Promise((resolve, reject) => {
				uni.request({
					url:'/api/user/login',
					method: 'post',
					header:{ 
					  'content-type':'application/x-www-form-urlencoded'
					},
					data: params,
					success: (res) => {
						if(res.data.code===200){
							setToken(res.data.data.userId);
							commit('SET_USERINFO', res.data.data)
							commit('SET_TOKEN', res.data.data.userId);
							resolve();
						}else{
							uni.showToast({
								icon:'error',
								position: 'bottom',
								title: '出错'+res.data.msg
							})
						}
						
					},
					fail(error) {
						uni.showToast({
							icon:'error',
							position: 'bottom',
							title: '出错'+error
						})
					}
				})
            }).catch(error=>{
				reject(error)
			})
        },
        GetUserInfo({commit}) {
            return new Promise((resolve, reject) => {
				uni.request({
					url:'/api/user/getUserInfo',
					method: 'get',
					success: (res) => {
						if(res.data.code===500){
						    commit('SET_USERINFO', '')
						    commit('SET_TOKEN', '');
						    removeToken();
						}
						commit('SET_USERINFO', res.data.data)
						commit('SET_LOGIN_STATUS', true);
						resolve();
					}
				})
                // getUserInfo().then(res => {
                    // if(res.data.code===500){
                    //     commit('SET_USERINFO', '')
                    //     commit('SET_TOKEN', '');
                    //     removeToken();
                    // }
                    // commit('SET_USERINFO', res.data.data)
                    // commit('SET_LOGIN_STATUS', true);
                    // resolve();
                // }).catch(error => {
                //     reject(error);
                // })
            }).catch(error=>{
				reject(error)
			})
        },
        Logout({commit}) {
            return new Promise((resolve) => {
                    commit('SET_USERINFO', '')
                    commit('SET_TOKEN', '');
                    removeToken();
                    resolve();
            })
        }
    },

    getters: {}


}

export default user;
